package com.swordget.service.impl;

import com.swordget.dao.TableDefinitionV2Dao;
import com.swordget.entity.ColumnDesign;
import com.swordget.entity.TableDesign;
import com.swordget.service.TableDefinitionV2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TableDefinitionV2ServiceImpl implements TableDefinitionV2Service {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TableDefinitionV2Dao tableDefinitionV2Dao;


    @Override
    public boolean initTableCols(TableDesign tableDesign, List<ColumnDesign> columnDesigns) {
        List<ColumnDesign> allCols = new ArrayList<>();
        allCols.addAll(columnDesigns);
        allCols.add(tableDefinitionV2Dao.getSerialCol());
        allCols.addAll(tableDefinitionV2Dao.getCommonCols());
        List<String> commands = tableDefinitionV2Dao.getColInsertSql(tableDesign, allCols);
        jdbcTemplate.batchUpdate(commands.toArray(new String[0]));
        return true;
    }

    @Override
    public boolean clearData(String tableName, String tableId) {
        //首先清除表定义数据
        String deleteTableDesign = String.format("DELETE FROM TABLEDESIGN WHERE SERIALNO = '%s' AND TABLENAME = '%s'",
                tableId, tableName);
        String deleteColumnDesign = String.format("DELETE FROM TABLEDEFINITION WHERE TABLEID = '%s'",
                tableId);
        jdbcTemplate.execute(deleteTableDesign);
        jdbcTemplate.execute(deleteColumnDesign);
        return true;
    }


    @Override
    public String hasRepeatCols(List<ColumnDesign> columnDesigns) {
        StringBuffer error=new StringBuffer("");
        Map<String, String> tempMap = new HashMap<>();
        columnDesigns.forEach(columnDesign -> {
            if (Objects.nonNull(tempMap.get(columnDesign.getName()))) {
                error.append(columnDesign.getName());
                error.append(",");
            }else{
                tempMap.put(columnDesign.getName(), "");
            }
        });
        return error.toString();
    }


}